package com.edu.nf.handle;

import com.edu.nf.util.BeanUtil;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class RowProcessor {


    /**
     * 将结果集转换成Bean对象
     * @param rs
     * @param type
     * @param <T>
     * @return
     * @throws SQLException
     *
     * rs:结果集，type:Teacher.class
     */
    public static <T>T toBean(ResultSet rs,Class<T> type) throws SQLException {
        return (T)BeanUtil.creatBean(rs,type);
    }


    /**
     * 将结果集转换成数组
     * @param rs
     * @return
     * @throws SQLException
     */
    public static Object[] toArray(ResultSet rs) throws SQLException{

        ResultSetMetaData metaData = rs.getMetaData();

        Object[] objects = new Object[metaData.getColumnCount()];

        for (int i=0;i<objects.length;i++){
            //数据库下标从一开始
            objects[i] = rs.getObject(i+1);
           // System.out.println(objects[i]);

        }
        return objects;
    }

    /**
     * 将一个结果集转换成map集合
     * @param rs
     * @return
     * @throws SQLException
     */
    public static Map<String,Object> toMap(ResultSet rs) throws SQLException{
        Map<String,Object> map = new HashMap<String,Object>();
        ResultSetMetaData metaData = rs.getMetaData();
        for (int i=1;i<=metaData.getColumnCount();i++){
            map.put(metaData.getColumnLabel(i),rs.getObject(i));
        }
        return map;
    }

    /**
     * 将一个结果集转换成一个值
     * @param rs
     * @param columnIndex
     * @param
     * @param
     * @return
     */
    public static Object toValue(ResultSet rs,int columnIndex) throws SQLException{
        Object value = rs.getObject(columnIndex);
        return value;
    }


}
